<template>
  <div class="dept-tree-select">
    <el-cascader
      v-model="selectedValue"
      :options="deptOptions"
      :props="{
        checkStrictly: true,
        value: 'deptId',
        label: 'deptName',
        emitPath: false
      }"
      :placeholder="placeholder"
      clearable
      :style="{ width: width }"
      class="filter-item"
      @change="handleChange"
    />
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'DeptTreeSelect',
  props: {
    value: {
      type: [Number, String],
      default: undefined
    },
    placeholder: {
      type: String,
      default: '选择部门'
    },
    width: {
      type: String,
      default: '300px'
    },
    deptTypes: {
      type: Array,
      default: () => [0, 1, 2, 3] // 默认保留合作社、烟站、乡镇、乡村组的类型
    }
  },
  data() {
    return {
      deptOptions: [], // 部门树形数据
      selectedValue: this.value
    }
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal
    }
  },
  created() {
    this.fetchDeptTree() // 获取部门树
  },
  methods: {
    // 获取部门树
    async fetchDeptTree() {
      try {
        const response = await request.get('/departments/tree')
        this.deptOptions = this.filterDeptTree(response)
      } catch (error) {
        console.error('获取部门树失败:', error)
        this.$message.error('获取部门树失败')
      }
    },

    // 过滤部门树,只保留指定类型
    filterDeptTree(deptTree) {
      return deptTree.filter(dept => {
        if (this.deptTypes.includes(dept.deptType)) {
          if (dept.children && dept.children.length > 0) {
            dept.children = this.filterDeptTree(dept.children)
          }
          return true
        }
        return false
      })
    },

    // 处理部门选择变化
    handleChange(value) {
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style lang="scss" scoped>
.dept-tree-select {
  display: inline-block;
}
</style> 